package com.allwees.core.dao.mybatis.dao;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.allwees.core.dao.DbException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

public interface BaseDao<T> extends BaseMapper<T> {

	boolean deleteByUuid(String uuid);

	default T findByUuid(String uuid) {
		if(StringUtils.isBlank(uuid)) {
			return null;
		}
		return selectOne(new QueryWrapper<T>().eq("uuid", uuid));
	}

	default boolean isExist(String fieldName, String value) {
		QueryWrapper<T> wrapper = new QueryWrapper<T>().eq(fieldName, value);
		return 0 < selectCount(wrapper);
	}

	default T findUniqueByField(String fieldName, String value) {
		QueryWrapper<T> wrapper = new QueryWrapper<T>().eq(fieldName, value);
		int count = selectCount(wrapper);
		if(count == 0) {
			return null;
		} else if(count > 1) {
			String msg = String.format("记录不唯一: 条件[%s: %s]存在 %d 条记录", fieldName, value, count);
			throw new DbException(msg);
		}
		return selectOne(wrapper);
	}

	default T findOneByField(String fieldName, String value) {
		if(StringUtils.isBlank(fieldName) || StringUtils.isBlank(value)) {
			return null;
		}
		return selectOne(new QueryWrapper<T>().eq(fieldName, value));
	}

	default List<T> findListByField(String fieldName, String value) {
		if(StringUtils.isBlank(fieldName) || StringUtils.isBlank(value)) {
			return null;
		}
		return selectList(new QueryWrapper<T>().eq(fieldName, value));
	}

	default List<T> findByUuids(Set<String> uuids) {
		if(CollectionUtils.isEmpty(uuids)) {
			return new ArrayList<>(0);
		}
		return selectList(new QueryWrapper<T>().in("uuid", uuids));
	}

	default List<T> findListByFieldValues(String fieldName, Set<Object> values) {
		if(CollectionUtils.isEmpty(values) || StringUtils.isBlank(fieldName)) {
			return new ArrayList<>();
		}
		return selectList(new QueryWrapper<T>().in(fieldName, values));
	}

	default boolean create(T t) {
		Assert.notNull(t, "t cannot be a null");
		int result = insert(t);
		return result > 0;
	}

	default int updateByUuid(T t, String uuid) {
		if(StringUtils.isBlank(uuid) || t == null) {
			return 0;
		}
		return update(t, new QueryWrapper<T>().eq("uuid", uuid));
	}

	default int updateByUuids(T t, Collection<String> uuids) {
		if(CollectionUtils.isEmpty(uuids) || t == null) {
			return 0;
		}
		return update(t, new QueryWrapper<T>().in("uuid", uuids));
	}

	default int deleteByUuids(Set<String> uuids) {
		if(CollectionUtils.isEmpty(uuids)) {
			return 0;
		}
		return delete(new QueryWrapper<T>().in("uuid", uuids));
	}
}
